package com.halflife.comeElectricity.batteryBox;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.halflife.comeElectricity.basic.address.Address;
import com.halflife.comeElectricity.battery.Battery;
import com.halflife.comeElectricity.battery.BatteryRepository;
import com.halflife.framework.converter.MapHandler;
import com.halflife.framework.domain.Page;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class BatteryBoxAdminController {

    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private BatteryBoxRepository batteryBoxRepository;
    @Resource
    private BatteryRepository batteryRepository;
    @Resource
    private RestTemplate template;

    @RequestMapping("/batteryBox/list")
    public String gotoList(@RequestParam(required = false) HashMap<String,Object> queryParam, Page page, HttpServletResponse response,
                           HttpServletRequest request, Model model) {
        MapHandler.handleMap(queryParam);
        if (page == null) {
            page = new Page();
        }
        page.setQueryParam(queryParam);
        int totalCount = batteryBoxRepository.selectCount(queryParam);
        List<BatteryBox> list = batteryBoxRepository.selectListByPage(queryParam);
        page.setTotalCount(totalCount);
        page.setMode(model);
        model.addAttribute("list",list);
        model.addAttribute("queryParam",queryParam);
        return "batteryBox/list";
    }

    @RequestMapping("/batteryBox/operate")
    public String gotoOperate(Integer id,Integer batteryCabinetId,HttpServletResponse response,
                               HttpServletRequest request, Model model) {
        BatteryBox batteryBox = new BatteryBox();
        if(id!=null){
            batteryBox = batteryBoxRepository.selectByPrimaryKey(id);
            batteryCabinetId = batteryBox.getBatteryCabinetId();
        }else{
            batteryBox = new BatteryBox();
            batteryBox.setBatteryCabinetId(batteryCabinetId);
        }
        model.addAttribute("batteryBox",batteryBox);
        return "batteryBox/operate";
    }

    @RequestMapping("/batteryBox/status")
    public String gotoStatus(Integer id,String no,Integer batteryCabinetId,HttpServletResponse response,
                               HttpServletRequest request, Model model) {
        Gson gson = new Gson();
        String result1 = template.getForObject("http://47.105.65.229:9898/refreshdata?lockerId="+no, String.class);
        String result = template.getForObject("http://47.105.65.229:9898/queryState?lockerId="+no, String.class);
        Result s =  gson.fromJson(result, Result.class);
        model.addAttribute("list", s.state);
        model.addAttribute("id", id);
        model.addAttribute("no", no);
        return "batteryBox/status";
    }

    @PostMapping("/batteryBox/save")
    @ResponseStatus(HttpStatus.CREATED)
    public ResponseEntity save(BatteryBox batteryBox,String batteryNo, HttpServletRequest request,
                              HttpServletResponse response, Model model) {
        try {
            Battery updateBattery = null;
            if (StringUtils.isNotBlank(batteryNo)) {
                Map<String, Object> param = new HashMap<>();
                param.put("no", batteryNo);
                List<Battery> list = batteryRepository.selectAll(param);
                if (list.size() > 0) {
                    Battery battery = list.get(0);
                    updateBattery = new Battery();
                    updateBattery.setId(battery.getId());
                    batteryBox.setBatteryId(battery.getId());
                }
                Battery battery = new Battery();
            }
            Integer id;
            if(batteryBox.getId()!=null){
                batteryBoxRepository.updateByPrimaryKey(batteryBox);
                id= batteryBox.getId();
            }else {
                batteryBox.init();
                id = batteryBoxRepository.insert(batteryBox);
            }
            if (updateBattery != null) {
                updateBattery.setBatteryBoxId(id);
                batteryRepository.updateByPrimaryKeySelective(updateBattery);
            }

        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(0, HttpStatus.OK);
    }

    @DeleteMapping("/batteryBox/delete")
    public ResponseEntity setRiderState(Integer id, Integer state) {
        try {
            BatteryBox batteryBox = new BatteryBox();
            batteryBox.setId(id);
            batteryBox.setValid(Boolean.FALSE);
            batteryBoxRepository.updateByPrimaryKeySelective(batteryBox);
        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(0, HttpStatus.OK);
    }
}
